package com.ocom.payconfig.controller;


import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityXfPointInfo;
import com.ocom.common.entity.payconfig.EntityDishesPoint;
import com.ocom.common.entity.payconfig.EntityMealPlan;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.GetPointDishesRequest;
import com.ocom.common.request.payconfig.SaveDishesPlacesRequest;
import com.ocom.common.request.payconfig.food.ComMerchRequest;
import com.ocom.common.request.payconfig.food.ComPointRequest;
import com.ocom.common.request.payconfig.food.DishesPlaceListRequest;
import com.ocom.common.request.payconfig.mealorder.GetOrderDishesInfoDao;
import com.ocom.common.request.payconfig.mealorder.GetOrderPlanDishesResponse;
import com.ocom.common.request.xfrecde.XfGoodListByPointIdRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.payconfig.PlanListVo;
import com.ocom.common.utils.*;
import com.ocom.common.vo.payconfig.*;
import com.ocom.common.vo.xfrecode.DishesIdNumVo;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.DishesPointService;
import com.ocom.payconfig.service.MealMenuService;
import com.ocom.payconfig.service.MealPlanService;
import com.ocom.payconfig.service.XfPointInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 11.10菜品摆放管理
 */

@Slf4j
@RestController
public class MachDishesController {

    @Autowired
    private XfPointInfoService xfPointInfoService;

    @Autowired
    private DishesPointService dishesPointService;

    @Autowired
    private MealPlanService mealPlanService;

    @Autowired
    private MealMenuService mealMenuService;

    @Autowired
    private XfRecordFeign xfRecordFeign;


    //11.10.1已排餐餐厅列表（getPlanPointList）
    @PostMapping(PayConfigUrl.Url_getPlanPointList)
    public Result getPlanPointList(@RequestBody ComMerchRequest request) {
        return ResultUtil.success(mealPlanService.getMealPlanPointList(request.getComId(), request.getMerchId()));
    }

    //11.10.2菜品摆放计划（getPlacePlanList）
    @PostMapping(PayConfigUrl.Url_getPlacePlanList)
    public Result getPlacePlanList(@RequestBody ComPointRequest request) {
        return ResultUtil.success(dishesPointService.getPlacePlanList(request.getComId(), 0, request.getPointId()));
    }


    //11.10.3菜品摆放方案（getDishesPlaceList）
    @PostMapping(PayConfigUrl.Url_getDishesPlaceList)
    public Result getDishesPlaceList(@RequestBody DishesPlaceListRequest request) {
        //复制来自11.4.1
        EntityMealPlan entityMealPlan = mealPlanService.upToDateMealPlanInfo(
                request.getComId(),
//				request.getMerchId(),
                request.getPointId(),
                null,
                request.getMealDate()
        );
        if (entityMealPlan == null) {
            return ResultUtil.success(null);
        }

        List<GetOrderDishesInfoDao> dishesInfoDaos = mealMenuService.getDishesInfo(request.getComId(), entityMealPlan.getMealplanId(), entityMealPlan.getDays(), request.getMealNo());

        if (dishesInfoDaos.size() == 0) {
            return ResultUtil.success(null);
        }

        List<GetOrderPlanDishesResponse> responseList = new ArrayList<>();

        for (GetOrderDishesInfoDao dishesInfoDao : dishesInfoDaos) {
            GetOrderPlanDishesResponse response = new GetOrderPlanDishesResponse();
            response.setMealMenuId(entityMealPlan.getMealplanId());
            response.setMealNo(dishesInfoDao.getMealNo());
            response.setDishesId(dishesInfoDao.getDishesId());
            response.setDishesName(dishesInfoDao.getDishesName());
            response.setPhotoUrl(dishesInfoDao.getPhotoUrl());
            response.setRemark(dishesInfoDao.getRemark());
            response.setDishesClassId(dishesInfoDao.getDishesClassId());
            response.setSort(dishesInfoDao.getSort());
            response.setPriceInfo(dishesInfoDao.getPriceInfo());

            if (org.apache.commons.lang3.StringUtils.isNotBlank(dishesInfoDao.getPriceInfo())) {
                try {
                    List<GetOrderPlanDishesResponse.Price> priceList = new ArrayList<>();

                    String[] price1 = dishesInfoDao.getPriceInfo().split(";");
                    for (String str : price1) {
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(str)) {
                            GetOrderPlanDishesResponse.Price price = new GetOrderPlanDishesResponse.Price();
                            String[] price2 = str.split(",");
                            price.setPriceMode(price2[0]);
                            price.setDishesPrice(price2[1]);
                            price.setDishesPriceNew(price2[2]);
                            price.setLimitedQuantity(price2[3]);
                            priceList.add(price);
                        }
                    }
                    response.setPriceList(priceList);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            responseList.add(response);
        }

        List<PlanListVo> list = new ArrayList<>();
        for (GetOrderPlanDishesResponse getOrderPlanDishesResponse : responseList) {
            for (GetOrderPlanDishesResponse.Price price : getOrderPlanDishesResponse.getPriceList()) {
                PlanListVo planListVo = new PlanListVo();
                planListVo.setDishesId(getOrderPlanDishesResponse.getDishesId());
                planListVo.setDishesName(getOrderPlanDishesResponse.getDishesName());
                planListVo.setPriceMode(Integer.valueOf(price.getPriceMode()));
                planListVo.setOrderNumber(0);
                planListVo.setPlaceIds("");
                planListVo.setPlaces("");
                list.add(planListVo);
            }
        }

        //place

        List<EntityDishesPoint> pointPlace = dishesPointService.getPointPlace(request.getComId(), request.getPointId(), request.getMealDate(), request.getMealNo());

        if (pointPlace.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                PlanListVo planListVo = list.get(i);
                for (EntityDishesPoint entityDishesPoint : pointPlace) {
                    if (entityDishesPoint.getDishesId().equals(planListVo.getDishesId())
                            && entityDishesPoint.getPriceMode().equals(planListVo.getPriceMode())
                    ) {
                        planListVo.setPlaceIds(planListVo.getPlaceIds() + "," + entityDishesPoint.getPlaceId());
                        planListVo.setPlaces(planListVo.getPlaces() + "," + entityDishesPoint.getPlaceName());
                        planListVo.setPlaces(StringUtils.trim(planListVo.getPlaces(),","));
                    }
                }

            }
        }

        //number
        XfGoodListByPointIdRequest xfGoodListByPointIdRequest = new XfGoodListByPointIdRequest();
        xfGoodListByPointIdRequest.setComId(request.getComId());
        xfGoodListByPointIdRequest.setPointId(request.getPointId());
        xfGoodListByPointIdRequest.setMealDate(request.getMealDate());
        xfGoodListByPointIdRequest.setMealNo(request.getMealNo());
        Result result = xfRecordFeign.getXfGoodListByPointId(xfGoodListByPointIdRequest);
        List<DishesIdNumVo> dishesIdNumVoList = JSON.parseArray(JSON.toJSONString(result.getData()), DishesIdNumVo.class);

        for (int i = 0; i < list.size(); i++) {
            PlanListVo planListVo = list.get(i);
            for (DishesIdNumVo dishesIdNumVo : dishesIdNumVoList) {
                if (dishesIdNumVo.getDishesId().equals(planListVo.getDishesId())) {
                    planListVo.setOrderNumber(dishesIdNumVo.getOrderNumber());
                }
            }
        }

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("planList", list);
        return ResultUtil.success(resMap);
    }

    //11.10.4餐厅下级消费点列表（getSubPointList）
    @PostMapping(PayConfigUrl.Url_getSubPointList)
    public Result getSubPointList(@RequestBody ComPointRequest request) {
        List<Integer> classIds =new ArrayList<>();
        classIds.add(request.getPointId());
        List<EntityXfPointInfo> list = xfPointInfoService.getAllChildPoint(request.getComId(), request.getPointId());
        if (list.size()>0) {
            classIds = list.stream().map(EntityXfPointInfo::getPointId).collect(Collectors.toList());
        }
        return ResultUtil.success( xfPointInfoService.getTollPointList(request.getComId(),classIds));
    }

    //11.10.5保存菜品摆放位置（saveDishesPlaces）
    @PostMapping(PayConfigUrl.Url_saveDishesPlaces)
    public Result saveDishesPlaces(@RequestBody SaveDishesPlacesRequest request) {
        dishesPointService.savePointPlaceBatch(request.getComId(),request);
        return ResultUtil.success();
    }


    //11.10.6下级消费点菜品信息（getPointDishes）
    @PostMapping(PayConfigUrl.URL_getPointDishes)
    public Result getPointDishes(@RequestBody GetPointDishesRequest request) {

        try {
            String pointOrg = "";
            if (request.getPointId() == 0) {
                pointOrg = "0";
            } else {
                EntityXfPointInfo entityXfPointInfo = xfPointInfoService.getTollPointInfo(request.getComId(), request.getPointId());
                if (entityXfPointInfo == null) {
                    return ResultUtil.error(ResultEnum.Err_4075);
                }
                if (CommonUtil.isNull(entityXfPointInfo.getPointOrgin())) {
                    pointOrg = "0";
                } else {
                    pointOrg = entityXfPointInfo.getPointOrgin();
                }
            }
            pointOrg = StringUtils.trim(pointOrg, ",");
            DishesPointOrgVo dishesPointOrgVo = dishesPointService.selectPoint(request.getComId(), pointOrg);

            Integer resPoint = 0;

            if(dishesPointOrgVo!=null){
                resPoint = dishesPointOrgVo.getRestPoint();
            }
            EntityDishesPoint entityDishesPoint = dishesPointService.selectLastDate(request.getComId(),
                    resPoint,
                    request.getMealNo(),
                    DateUtil.getDate(request.getMealDate(), "yyyy-MM-dd")
            );
            String resMealDate = DateUtil.getDate();
            if(entityDishesPoint!=null){
                resMealDate =   DateUtils.dateTime(entityDishesPoint.getMealDate());
            }
//            pointOrg = pointOrg + "," + request.getPointId();
//            pointOrg = StringUtils.trim(pointOrg, ",");
//            pointOrg = pointOrg.replace(",,", ",");

//            List<String> isStr = Arrays.asList(pointOrg.split(","));
//            List<Integer> isInt = new ArrayList<>();
//            CollectionUtils.collect(isStr, new Transformer() {
//                @Override
//                public Object transform(Object obj) {
//                    return Integer.valueOf(obj.toString());
//                }
//            }, isInt);
            List<Integer> isInt = new ArrayList<>();
            isInt.add(request.getPointId());

            List<DishesPointListVo> dishesPointListVos = dishesPointService.selectPointDishes(
                    request.getComId(),
                    resPoint,
                    resMealDate,
                    request.getMealNo(),
                    request.getPointId(),
                    isInt
            );


            GetPointDishesVo getPointDishesVo = new GetPointDishesVo();

            for (DishesPointListVo dishesPointListVo : dishesPointListVos) {
                List<Integer> pointIds = getPointDishesVo.getPointList().stream().map(PointDishesPointListVo -> PointDishesPointListVo.getPointId()).collect(Collectors.toList());
                if (pointIds.contains(dishesPointListVo.getDishesPoint())) {

                    int jk = 0;
                    for (int i = 0; i < getPointDishesVo.getPointList().size(); i++) {
                        PointDishesPointListVo pointDishesPointListVo = getPointDishesVo.getPointList().get(i);
                        if (pointDishesPointListVo.getPointId().equals(dishesPointListVo.getDishesPoint())) {
                            jk = i;
                            break;
                        }
                    }
                    PointDishesPointListDishesListVo pointDishesPointListDishesListVo = new PointDishesPointListDishesListVo();
                    pointDishesPointListDishesListVo.setDishesId(dishesPointListVo.getDishesId());
                    pointDishesPointListDishesListVo.setDishesName(dishesPointListVo.getDishesName());
                    pointDishesPointListDishesListVo.setPhotoUrl(dishesPointListVo.getPhotoUrl());
                    getPointDishesVo.getPointList().get(jk).getDishesList().add(pointDishesPointListDishesListVo);

                } else {
                    PointDishesPointListVo pointDishesPointListVo = new PointDishesPointListVo();
                    pointDishesPointListVo.setPointId(dishesPointListVo.getDishesPoint());
                    pointDishesPointListVo.setPointName(dishesPointListVo.getPointName());

                    PointDishesPointListDishesListVo pointDishesPointListDishesListVo = new PointDishesPointListDishesListVo();
                    pointDishesPointListDishesListVo.setDishesId(dishesPointListVo.getDishesId());
                    pointDishesPointListDishesListVo.setDishesName(dishesPointListVo.getDishesName());
                    pointDishesPointListDishesListVo.setPhotoUrl(dishesPointListVo.getPhotoUrl());
                    pointDishesPointListVo.getDishesList().add(pointDishesPointListDishesListVo);
                    getPointDishesVo.getPointList().add(pointDishesPointListVo);
                }
            }
            return ResultUtil.success(getPointDishesVo);
        } catch (Exception e) {
            log.error("【获取餐品信息异常】【{}】", e);
            return ResultUtil.error(ResultEnum.Err_4005);
        }
    }

}
